
package com.ruhua.java.service;

import com.ruhua.java.dao.Admin;
import com.ruhua.java.exception.ErrException;
import com.ruhua.java.exception.NotFoundException;
import com.ruhua.java.repository.AdminRepository;
import com.ruhua.java.util.CommonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.Optional;


@Service
public class AdminService {
    @Autowired
    AdminRepository adminRepository;

    public Admin getById(Long num) {
        return adminRepository.findOneById(num);
    }

    public Optional<Admin> getByName(String name) {
        return adminRepository.findByUsername(name);
    }


    public Admin getUserById(Long id) {
        Optional<Admin> oadmin=adminRepository.findById(id);
        return oadmin.orElseThrow(()->new ErrException("用户不存在"));
    }


    public Admin findAdmin(String username,String psw){
        Optional<Admin> oadmin=adminRepository.findNamePsw(username,psw);
        return oadmin.orElseThrow(()-> new ErrException("账号或密码错误"));
    }
    public List<Admin> findAll(){
        return adminRepository.findAll();
    }

    public void addAdmin(Map<String,Object> person){
        String username=person.get("username").toString();
        String gid=person.get("group_id").toString();
        Long group_id=Long.parseLong(gid);
        String password=person.get("password").toString();
        password = CommonUtil.md5(password);
        String desc=person.get("description").toString();
        Admin item = Admin.builder()
                .username(username)
                .groupId(group_id)
                .password(password)
                .description(desc)
                .build();
        adminRepository.save(item);
    }

    public void delItem(Long id) {
        try {
            adminRepository.deleteById(id);
        } catch (Exception e) {
            throw new NotFoundException(10001);
        }
    }
}
